package admin_service

import (
	"shop/config/constant"
	"shop/dao"
	"shop/entity"
	"shop/utils/genutil"
	"shop/utils/result"
	"shop/utils/sessionutil"
)

type LoginParams struct {
	Account  string `json:"account"`
	Password string `json:"password"`
}

// Login 手机或用户名+密码登录
func Login(params *LoginParams) *result.Result {
	user := &entity.SysUser{}
	if len(params.Account) > 0 {
		dao.GetDB().Model(user).Where("phone", params.Account).Take(user)
	}
	if user.Id == 0 {
		dao.GetDB().Model(user).Where("username", params.Account).Take(user)
	}
	if user.Id == 0 {
		return result.Fail("手机账号和用户名都不存在")
	}

	// 验证密码
	password := genutil.Md5HexWithSalt(params.Password, user.Salt)
	if user.Password != password {
		return result.Fail("密码不正确")
	}

	return result.Ok(sessionutil.SetSysUserSession(sessionutil.GetSysUserInfo(user.Id)))
}

func LoginByPhone(phone, code string) *result.Result {
	cacheK := constant.CacheKeyPrefixVerifyCodeSysUserLogin + phone // 一个phone对应一个code
	realCode := dao.GetRedisCli().Get(cacheK).Val()
	if realCode == "" {
		return result.Fail("验证码不存在或已经过期")
	}
	if realCode != code {
		return result.Fail("验证码不正确")
	}
	dao.GetRedisCli().Del(cacheK)

	user := &entity.SysUser{}
	dao.GetDB().Model(user).Where("phone", phone).Take(user)
	if user.Id == 0 {
		return result.Fail("用户不存在")
	}
	return result.Ok(sessionutil.SetSysUserSession(sessionutil.GetSysUserInfo(user.Id)))
}
